//
//  EveryDayDetailViewController.m
//  littleLight's Project-A
//
//  Created by dllo on 16/5/17.
//  Copyright © 2016年 light. All rights reserved.
//



#import "EveryDayDetailViewController.h"
#import <AFNetworking.h>
#import "SpotModel.h"
#import "TripModel.h"
#import <UIImageView+WebCache.h>
#import "EverydayDetailFisrtCell.h"
#import "UserViewController.h"
@interface EveryDayDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *storyTableView;
@property (nonatomic, strong) NSMutableArray *spotArray;
@property (nonatomic, strong) NSMutableArray *tripArray;
@property (nonatomic, strong) NSMutableArray *allArray;
@property (nonatomic, strong) NSNumber *userNumber;
@property (nonatomic, strong) SpotModel *model;
@end

@implementation EveryDayDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.spotArray = [NSMutableArray array];
    self.allArray = [NSMutableArray array];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:192 / 255.0 blue:203 / 255.0 alpha:1];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Cancel2"] imageWithRenderingMode:1]style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];
   
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"shoucang-1"] imageWithRenderingMode:1]style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];
    self.navigationItem.title = @"故事详情";
    //字体设为白色
   
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName: [UIFont systemFontOfSize:22]}];
    self.storyTableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.storyTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.storyTableView];
    NSLog(@"%@",self.spot_id);
    self.storyTableView.dataSource = self;
    self.storyTableView.delegate = self;
    [self.storyTableView registerClass:[EverydayDetailFisrtCell class] forCellReuseIdentifier:@"reuse"];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *string = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/new_trip/spot/?spot_id=%@",self.spot_id];
    [manager GET:string parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDic = [responseObject objectForKey:@"data"];
        NSDictionary *spotDic = [dataDic objectForKey:@"spot"];
        
        SpotModel *spModel = [[SpotModel alloc] init];
        [spModel setValuesForKeysWithDictionary:spotDic];
        
      
        [self.allArray addObject:spModel];
        
        NSLog(@"%ld",self.allArray.count);
        NSDictionary *tripDic = [dataDic objectForKey:@"trip"];
        TripModel *trModel = [[TripModel alloc] init];
     //  NSLog(@"***************%@",spModel.itText);
        
        [trModel setValuesForKeysWithDictionary:tripDic];
       
        
     //   [self.allArray addObject:trModel];
        NSLog(@"%ld",self.allArray.count);
        
        //设置头视图
       
        //计算文字高度
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil];
        //这里的宽度一定要和我们显示文字的label的宽度一样;
        CGRect rect = [spModel.itText boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 40 * sWidth, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
      
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150 * sHeight + rect.size.height + 10 * sHeight)];
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 * sWidth, 110 * sHeight, self.view.frame.size.width - 40 * sWidth, rect.size.height)];
        textLabel.numberOfLines = 0;
        textLabel.font = [UIFont systemFontOfSize:17];
        textLabel.font = [UIFont boldSystemFontOfSize:17];
        textLabel.text = spModel.itText;
        [headerView addSubview:textLabel];
        UIImageView *headImage = [[UIImageView alloc] initWithFrame:CGRectMake(20 * sWidth, 20 * sHeight, 60 *sWidth , 60 * sHeight)];
        headImage.layer.masksToBounds = YES;
        headImage.layer.cornerRadius = 30;
        [headerView addSubview:headImage];
        [headImage sd_setImageWithURL:[NSURL URLWithString:trModel.model.avatar_m]];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        [headImage addGestureRecognizer:tap];
        headImage.userInteractionEnabled = YES;
        self.userNumber = trModel.model.myId;
        
        self.storyTableView.tableHeaderView = headerView;
        
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(90 * sWidth, 20 * sHeight, 200 * sWidth, 40 * sHeight)];
        nameLabel.font = [UIFont systemFontOfSize:20];
        nameLabel.text = trModel.model.userName;
        [headerView addSubview:nameLabel];
        
        UILabel *storyLabel = [[UILabel alloc] initWithFrame:CGRectMake(90 * sWidth, 50 * sHeight, 80 * sWidth, 30 * sHeight)];
        storyLabel.text = @"故事发生在";
        storyLabel.font = [UIFont systemFontOfSize:14];
        [headerView addSubview:storyLabel];
       
        UILabel *addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(170 * sWidth, 50 *sHeight, 150 *sWidth, 30 *sHeight)];
        addressLabel.textColor = [UIColor cyanColor];
       // NSLog(@"====%@",spModel.model.name);
        addressLabel.text = spModel.name;
        addressLabel.font = [UIFont systemFontOfSize:14];
        [headerView addSubview:addressLabel];
        UILabel *countLabel = [[UILabel alloc] initWithFrame:CGRectMake(330 * sWidth, 50 *sHeight, 70 * sWidth, 30 * sHeight)];
        countLabel.font = [UIFont systemFontOfSize:14];
        countLabel.text = [NSString stringWithFormat:@"%@浏览",[spModel.view_count stringValue]];
        [headerView addSubview:countLabel];
        UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 * sWidth, 100 *sHeight , 374 * sWidth, 1 * sHeight)];
        lineLabel.backgroundColor = [UIColor grayColor];
        lineLabel.alpha = 0.5;
        [headerView addSubview:lineLabel];
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150 * sHeight)];
        
        
        UILabel *footLineLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 * sWidth, 10 *sHeight, 374 * sWidth, 1 * sHeight)];
        footLineLabel.backgroundColor = [UIColor grayColor];
        footLineLabel.alpha = 0.5;
        [footView addSubview:footLineLabel];
        UIImageView *cameraImage = [[UIImageView alloc] initWithFrame:CGRectMake(20 * sWidth, 30 * sHeight, 24 *sWidth, 24 *sHeight)];
        cameraImage.image = [UIImage imageNamed:@"camera"];
        [footView addSubview:cameraImage];
        UIImageView *colckImage = [[UIImageView alloc] initWithFrame:CGRectMake(20 * sWidth, 80 *sHeight, 24 *sWidth, 24 *sHeight)];
        colckImage.image = [UIImage imageNamed:@"clock"];
        [footView addSubview:colckImage];
        UILabel *stoLbale = [[UILabel alloc] initWithFrame:CGRectMake(50 * sWidth, 30 * sHeight, 100 * sWidth, 25 * sHeight)];
        stoLbale.text = @"故事收录于";
        stoLbale.font = [UIFont systemFontOfSize:15];
        stoLbale.textColor = [UIColor grayColor];
        stoLbale.alpha = 0.8;
        [footView addSubview:stoLbale];
        
        UILabel *trNameLable = [[UILabel alloc] initWithFrame:CGRectMake(150 * sWidth, 30 * sHeight, 200 * sWidth, 25 *sHeight)];
        trNameLable.font = [UIFont systemFontOfSize:15];
        trNameLable.font = [UIFont boldSystemFontOfSize:12];
        trNameLable.text = trModel.myName;
        [footView addSubview:trNameLable];
      
        UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(50 * sWidth, 80 * sHeight, 200 * sWidth, 25 * sHeight)];
        timeLabel.font = [UIFont systemFontOfSize:15];
        timeLabel.font = [UIFont boldSystemFontOfSize:12];
        NSString *str1 = [spModel.date_tour substringToIndex:9];
        NSString *str2 = [spModel.date_tour substringWithRange:NSMakeRange(11, 5)];
        NSString *str3 = [NSString stringWithFormat:@"%@  %@",str1,str2];
        timeLabel.text = str3;
        [footView addSubview:timeLabel];
        self.storyTableView.tableFooterView = footView;
      //cell自适应高度
      //  self.storyTableView.rowHeight = UITableViewAutomaticDimension;
        
        self.model = spModel;
        
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.storyTableView reloadData];
        self.storyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
    
}

- (void)rightAction
{
   // NSLog(@"%ld",self.allArray.count);
    
//    SpotModel *spot = [self.allArray objectAtIndex:0];
////    SpotListModel *list = [spot.detail_list firstObject];
//    NSString *storyId = [self.spot_id  stringValue];
//
//    [[DataBaseHandle shareDataBaseHandle]insertStoryModel:spot withId:storyId];
    NSMutableArray *array = [[DataBaseHandle shareDataBaseHandle] selectAllStory];
   // NSLog(@"%@",self.model.itText);
    NSLog(@"%@",array);
    if ([array containsObject:self.model.itText]) {
        
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"这个故事已经被收藏~\(≧▽≦)/~啦啦啦" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                
            }]];
            [self presentViewController:alert animated:YES completion:^{
                
                
            }];
    }else{
        SpotModel *spot = [self.allArray objectAtIndex:0];
        //    SpotListModel *list = [spot.detail_list firstObject];
        NSString *storyId = [self.spot_id  stringValue];
        
        [[DataBaseHandle shareDataBaseHandle]insertStoryModel:spot withId:storyId];
    }
    
    
}


- (void)tapAction
{
    UserViewController *userVC = [[UserViewController alloc] init];
    userVC.myId = self.userNumber;
    [self.navigationController pushViewController:userVC animated:YES];
    
    
}



- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //NSLog(@"===%ld",section);
    if (self.allArray.count == 0) {
        
        return 0;
    }
    SpotModel *model = [self.allArray objectAtIndex:section];
   // return 1;
    
    
   // NSLog(@"===%ld",model.detail_list.count);
    
    return model.detail_list.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{    SpotModel *model = [self.allArray firstObject];
     SpotListModel *listModel = [model.detail_list objectAtIndex:indexPath.row];
    //计算文字高度
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil];
    //这里的宽度一定要和我们显示文字的label的宽度一样;
    CGRect rect = [listModel.myText boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    //rect.size.height 这就是文字的高度
    

    return 270 + rect.size.height;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    EverydayDetailFisrtCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    SpotModel *model = [self.allArray firstObject];
    SpotListModel *listModel = [model.detail_list objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = listModel;
    return cell;
}

- (void)leftAction
{

    
    if ([self.type isEqualToString:@"1"]) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
    
    
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
